package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Provider;


@Stateless
public class ProviderService {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Provider getById(Integer id){	
		return em.find(Provider.class, id);
	}
    
    public Provider save(Provider provider) {
    	em.persist(provider); 
    	return provider;
    }
    
    public Provider update(Provider provider) {
    	return em.merge(provider); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Provider.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Provider> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Provider e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
	
	//----------------------------------------------------------------------
	
	public Provider getByName(String name) {
		Provider result = null;
    	Query query = em.createQuery("SELECT e FROM Provider e WHERE e.name=:name");
    	query.setParameter("name", name);
    	try{
    		result = (Provider) query.getSingleResult();
    	}
    	catch(NoResultException e){
    	}
        return result; 
    }
	
	public Provider getByCode(Integer code) {
		Provider result = null;
    	Query query = em.createQuery("SELECT e FROM Provider e WHERE e.code=:code");
    	query.setParameter("code", code);
    	try{
    		result = (Provider) query.getSingleResult();
    	}
    	catch(NoResultException e){
    	}
        return result; 
    }
    
    
}

